package com.ydkj.a37e_mall.Classes.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.LoginActivity;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.OrderDetail;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.ProductDetails;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.CancelMallOrderReq;
import com.ydkj.a37e_mall.Classes.Model.Request.GetMallOrderListReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetMallOrderListResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/1/19.
 * （我的订单）已完成
 */

public class HadCompleteMallOrderFg extends BaseFragment {
    private View rootView;
    private Activity mActivity;
    private PullToRefreshListView plv_had_complete_order;
    private HadCompleteAdapter hadCompleteAdapter;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private List<GetMallOrderListResp.ResultEntity.DataEntity> had_Complete_list;
    private List<GetMallOrderListResp.ResultEntity.DataEntity> intentList;

    private static final int LOAD = 0;// 加载
    private static final int REFRESH = 1;// 刷新
    private static final int MORE = 2;// 更多
    private int page;
    private String secret;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.comment_good, container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        isPrepared = true;
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();

        init();


    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        plv_had_complete_order = (PullToRefreshListView) rootView.findViewById(R.id.listview_comment_all);

        had_Complete_list = new ArrayList<GetMallOrderListResp.ResultEntity.DataEntity>();
        intentList = new ArrayList<GetMallOrderListResp.ResultEntity.DataEntity>();

        hadCompleteAdapter = new HadCompleteAdapter(had_Complete_list);
        plv_had_complete_order.setAdapter(hadCompleteAdapter);
        plv_had_complete_order.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetCompleteOrderList(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetCompleteOrderList(MORE);
            }
        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        Log.e("ssss", "已完成");
        GetCompleteOrderList(REFRESH);
    }

    private class HadCompleteAdapter extends BaseAdapter {
        public List<GetMallOrderListResp.ResultEntity.DataEntity> had_Complete_list;

        public HadCompleteAdapter(List<GetMallOrderListResp.ResultEntity.DataEntity> infos) {
            if (infos == null) {
                infos = new ArrayList<GetMallOrderListResp.ResultEntity.DataEntity>();
            }
            had_Complete_list = infos;
        }

        @Override
        public int getCount() {
            return had_Complete_list.size();
        }

        @Override
        public GetMallOrderListResp.ResultEntity.DataEntity getItem(int position) {
            return had_Complete_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.order_had_complete_listitem, null);
                vh = new ViewHolder();
                vh.lly_all_product_order = (LinearLayout) convertView.findViewById(R.id.lly_all_product_order);
                vh.tv_order_states = (TextView) convertView.findViewById(R.id.tv_order_states);
                vh.tv_order_num = (TextView) convertView.findViewById(R.id.tv_order_num);
                vh.tv_status = (TextView) convertView.findViewById(R.id.tv_status);
                vh.tv_product_num = (TextView) convertView.findViewById(R.id.tv_product_num);
                vh.tv_all_product_price = (TextView) convertView.findViewById(R.id.tv_all_product_price);
                vh.tv_give_integral = (TextView) convertView.findViewById(R.id.tv_give_integral);
                vh.tv_upload_voucher = (TextView) convertView.findViewById(R.id.tv_upload_voucher);
                vh.tv_see_logistics = (TextView) convertView.findViewById(R.id.tv_delete_order);
                vh.tv_confirm_receipt = (TextView) convertView.findViewById(R.id.tv_see_logistics);
                vh.rly_had_complete = (RelativeLayout) convertView.findViewById(R.id.rly_had_complete);
                vh.rly_orderdetail = (RelativeLayout) convertView.findViewById(R.id.rly_orderdetail);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            vh.tv_see_logistics.setText("换货");
            vh.tv_confirm_receipt.setVisibility(View.GONE);
            vh.tv_order_states.setText("普通订单");
            vh.tv_order_num.setText(getItem(position).getSn());//订单号
            vh.tv_status.setText("已完成");//状态
            vh.tv_product_num.setText("共计" + getItem(position).getNum() + "件商品");
            vh.tv_all_product_price.setText(getItem(position).getTotal_fee());


            vh.lly_all_product_order.removeAllViews();
            LinearLayout productLayout = (LinearLayout) LayoutInflater.from(mActivity).inflate(R.layout.mall_order_layout, null);
            ImageView img_thumb = (ImageView) productLayout.findViewById(R.id.img_thumb);
            TextView tv_describe = (TextView) productLayout.findViewById(R.id.tv_describe);
            TextView tv_price = (TextView) productLayout.findViewById(R.id.tv_price);
            TextView tv_postage = (TextView) productLayout.findViewById(R.id.tv_postage);
            TextView tv_type_content = (TextView) productLayout.findViewById(R.id.tv_type_content);
            TextView tv_num = (TextView) productLayout.findViewById(R.id.tv_num);

            tv_describe.setText(getItem(position).getInfo());
            tv_price.setText(getItem(position).getTotal_fee());
            for (int i = 0; i < getItem(position).getProduct().size(); i++) {
                if (i == 0) {
                    tv_type_content.setText(getItem(position).getProduct().get(i).getStandard_type() + ":"
                            + getItem(position).getProduct().get(i).getStandard_name());
                } else {
                    tv_type_content.setText(tv_type_content.getText().toString() + "\n" + getItem(position).getProduct().get(i).getStandard_type() + ":"
                            + getItem(position).getProduct().get(i).getStandard_name());
                }
            }
            tv_num.setText("X" + getItem(position).getNum());
            ImageLoader.getInstance().displayImage(getItem(position).getThumb(), img_thumb, displayImageOptions);


            vh.lly_all_product_order.addView(productLayout);


            //订单详情
            vh.rly_orderdetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intentList.clear();
                    intentList.add(had_Complete_list.get(position));
                    Intent intent = new Intent(getActivity(), OrderDetail.class);
                    intent.putExtra("intentList", (Serializable) intentList);
                    startActivity(intent);
                }
            });

            //商品详细
            productLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, ProductDetails.class);
                    intent.putExtra("id", getItem(position).getProduct_id());
                    startActivity(intent);
                }
            });


            //换货
            vh.tv_see_logistics.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CancelOrder(getItem(position).getId());

                }
            });


            return convertView;
        }

        public class ViewHolder {
            private RelativeLayout rly_orderdetail;

            private LinearLayout lly_all_product_order;
            private TextView tv_order_states, tv_order_num, tv_status, tv_product_num, tv_all_product_price, tv_give_integral;
            private TextView tv_upload_voucher, tv_see_logistics, tv_confirm_receipt;
            private RelativeLayout rly_had_complete;
        }
    }


    //获取已完成订单列表
    private void GetCompleteOrderList(final int type) {
        CustomProgressDialog.createDialog(mActivity).Show();
        GetMallOrderListReq req = new GetMallOrderListReq();
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = had_Complete_list.size() / 20 + 1;
        }
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setDelivery_type("1");
        req.setStats("6");
        req.setPage(page + "");
        req.setPage_size("10");

        RequestParams params = new RequestParams();

        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Log.e("url", "params==" + params);
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        CustomProgressDialog.Dismiss();
                        mHasLoadedOnce = true;
                        Log.e("url", "had_complete_order_json==" + response);
                        String errno = response.optString("errno");
                        String errmsg = response.optString("errmsg");
                        if (errmsg.equals("暂无订单")) {
                            had_Complete_list.clear();
                            hadCompleteAdapter.notifyDataSetChanged();
                            plv_had_complete_order.onRefreshComplete();
                            CommonUtil.showToast(mActivity, errmsg);
                            return;
                        }
                        if (errno.equals("000")) {
                            GetMallOrderListResp resp = GsonImpl.get().toObject(response.toString(), GetMallOrderListResp.class);
                            if (type == LOAD || type == REFRESH) {
                                had_Complete_list.clear();
                                had_Complete_list.addAll(resp.getResult().getData());
                            } else {
                                had_Complete_list.addAll(resp.getResult().getData());
                            }

                            if (had_Complete_list.size() % 10 > 0) {
                                plv_had_complete_order.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plv_had_complete_order.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                            hadCompleteAdapter.notifyDataSetChanged();
                            plv_had_complete_order.onRefreshComplete();
                        } else if (errno.equals("999")) {
                            CommonUtil.showToast(mActivity, errmsg);
                            Intent intent = new Intent(mActivity, LoginActivity.class);
                            startActivityForResult(intent, 2);
                            Log.e("url", "errmsg==" + errmsg);
                        } else if (errno.equals("008")) {
                            had_Complete_list.clear();
                            hadCompleteAdapter.notifyDataSetChanged();
                            plv_had_complete_order.onRefreshComplete();
//                    CommonUtil.showToast(mActivity, errmsg);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String
                            responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        CustomProgressDialog.Dismiss();
                        CommonUtil.showToast(mActivity, "网络连接失败");
                    }
                }

        );
    }

    //    //待付款取消订单
    private void CancelOrder(String id) {
        CustomProgressDialog.createDialog(mActivity).show();
        CancelMallOrderReq req = new CancelMallOrderReq();
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setReturned_delivery("");
        req.setDelivery_no("");
        req.setStats("7");

        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Log.e("ssss", "换货订单id==》" + id);

        String url = Const.COMMON_ADDRESS + req.urlString() + id;
        AsyncHttpClient client = new AsyncHttpClient();
        client.put(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "cancel_order_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    GetCompleteOrderList(REFRESH);
                    CommonUtil.showToast(mActivity, errmsg);

                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 1);
                    Log.e("url", "errmsg==" + errmsg);
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                    GetCompleteOrderList(REFRESH);
                    CustomProgressDialog.Dismiss();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }
}
